package com.zhouyu.user;

import com.zhouyu.spring.BeanPostProcessor;
import com.zhouyu.spring.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

@Component
public class ZhouyuBeanPostProcessor implements BeanPostProcessor {

	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName) {
		return BeanPostProcessor.super.postProcessBeforeInitialization(bean, beanName);
	}

	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) {
		if (beanName.equals("userService")) {
			Object proxyInstance = Proxy.newProxyInstance(ZhouyuBeanPostProcessor.class.getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler() {
				@Override
				public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
					System.out.println("切面前的逻辑，底层 AOP 的原理");

					// 执行 bean 的原始方法
					Object result = method.invoke(bean, args);

					System.out.println("切面后的逻辑，底层 AOP 的原理");

					return result;
				}
			});

			// 返回代理对象
			return proxyInstance;
		}

		return bean;
	}
}
